<template>
  <div class="outbox">
    <el-card class="chooseBox">
      <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc">
        用户列表<span style="font-size: 12px">（点击聊天气泡开始聊天）</span>
      </div>
      <div style="padding: 10px 0" v-for="user in users" :key="user.userid">
        <span>{{ user.username }}</span>
        <i
          class="el-icon-chat-dot-round"
          style="margin-left: 10px; font-size: 16px; cursor: pointer"
          @click="chooseChatUser(user.userid)"
        ></i>
        <span
          style="font-size: 12px; color: limegreen; margin-left: 5px"
          v-if="user.userid === chatUser"
          >chatting...</span
        >
      </div>
    </el-card>

    <div class="chat-outbox">
      <div style="text-align: center; line-height: 50px">
        {{ `Web聊天室（${chatUser}）` }}
      </div>
      <div class="chatBox" v-html="content" ref="chatBox"></div>
      <div style="padding: 20px">
        <div style="display: flex; justify-content: space-around">
          <el-input
            autosize
            placeholder="请输入内容"
            v-model="text"
            type="textarea"
            maxlength="2000"
            show-word-limit
          >
          </el-input>
          <div style="width: 20px"></div>
          <div>
            <el-button type="primary" @click="send">发送</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
let socket;

export default {
  name: "Im",
  data() {
    return {
      circleUrl:
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      user: {},
      // isCollapse: false,
      users: [],
      chatUser: "",
      text: "",
      // messages: [],
      content: "",
    };
  },
  created() {
    this.init();
  },
  methods: {
    scrollToBottom() {
      const chatBox = this.$refs.chatBox;
      chatBox.scrollTop = chatBox.scrollHeight;
    },
    send() {
      if (!this.chatUser) {
        this.$message({ type: "warning", message: "请选择聊天对象" });
        return;
      }
      if (!this.text) {
        this.$message({ type: "warning", message: "请输入内容" });
      } else {
        if (typeof WebSocket == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        } else {
          console.log("您的浏览器支持WebSocket");
          // 组装待发送的消息 json
          // {"from": "zhang", "to": "admin", "text": "聊天文本"}
          let timestamp = new Date().toISOString();
          let message = {
            from: this.user.userid,
            to: this.chatUser,
            text: this.text,
            timestamp: timestamp,
          };
          socket.send(JSON.stringify(message)); // 将组装好的json发送给服务端，由服务端进行转发
          // 构建消息内容，本人消息
          this.createContent(null, this.user.userid, this.text, timestamp);
          this.text = "";
          // 滚动到底部
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        }
      }
    },
    chooseChatUser(userId) {
      this.chatUser = userId;
      this.content = "";
      this.loadChatLogs(this.chatUser); // 加载聊天记录
      // 滚动到底部
      this.$nextTick(() => {
        setTimeout(() => {
          this.scrollToBottom();
        }, 100);
      });
    },
    loadChatLogs(userId) {
      this.$http
        .get(`/chatlogs/${userId}`)
        .then((response) => {
          let chatLogs = response.data;
          chatLogs.forEach((log) => {
            let senderType = log.senderType;
            let senderId = log.senderId;
            let message = log.message;
            let timestamp = log.timestamp;

            // 判断消息是不是本管理员发送的
            if (senderId == this.user.userid && senderType === "admin") {
              // 本管理员的消息，显示在右边
              this.createContent(null, senderId, message, timestamp);
            } else if (senderType === "parent") {
              // parent类型的消息，显示在左边，颜色为deepskyblue
              this.createContent(senderId, null, message, timestamp, true);
            } else {
              // admin类型的消息，也显示在左边，但颜色不同
              this.createContent(senderId, null, message, timestamp, false);
            }
          });
        })
        .catch((error) => {
          console.error("Error fetching chat logs:", error);
        });
    },
    createContent(remoteUser, nowUser, text, timestamp, isParent) {
      let html = "";
      let formattedTime = new Date(timestamp).toLocaleString();

      if (nowUser) {
        html = `
      <div class="message" style="padding: 5px 0;margin:0 20px">
        <div class="time-text" style="text-align: right;">
          <div style="text-align: right; font-size: small; color: gray;">${formattedTime}</div>
          <div class="tip left" style="white-space: pre-wrap;">${text}</div>
        </div>
        <div class="name-avatar" style="text-align: center;">
          <div style="font-size: small; color: gray;">管理员:${nowUser}</div>
          <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
            <img src="${this.circleUrl}" style="object-fit: cover;">
          </span>
        </div>
      </div>
    `;
      } else if (remoteUser) {
        const bubbleColor = isParent ? "deepskyblue" : "rgba(69, 137, 51,0.7)";
        const type = isParent ? "用户" : "管理员";
        html = `
      <div class="message2" style="padding: 5px 0">
        <div class="name-avatar" style="text-align: center;">
          <div style="font-size: small; color: gray;">${type}:${remoteUser}</div>
          <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
            <img src="${this.circleUrl}" style="object-fit: cover;">
          </span>
        </div>
        <div class="time-text" style="text-align: left; padding-left: 10px">
          <div style="text-align: left; font-size: small; color: gray;">${formattedTime}</div>
          <div class="tip right" style="white-space: pre-wrap;background-color: ${bubbleColor}">${text}</div>
        </div>
      </div>
    `;
      }
      this.content += html;
    },

    init() {
      let adminid = this.$store.getters.id;
      this.user = { userid: adminid };
      let userid = this.user.userid;
      let _this = this;
      if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        let socketUrl = this.$socketURL + "/imserver/admin/" + userid;
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {
          console.log("websocket已打开");
        };
        //  浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function (msg) {
          console.log("收到数据====" + msg.data);
          let data = JSON.parse(msg.data); // 对收到的json数据进行解析， 类似这样的： {"users": [{"userid": "zhang"},{ "userid": "admin"}]}
          if (data.users) {
            // 获取在线人员信息
            _this.users = data.users;
          }
          // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
          // {"from": "zhang", "text": "hello","timestamp":"xxx"}
          if (data.from === _this.chatUser) {
            _this.createContent(data.from, null, data.text, data.timestamp);
          }
        };
        //关闭事件
        socket.onclose = function () {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
          console.log("websocket发生了错误");
        };
      }
    },
  },
};
</script>


<style scoped>
.chat-outbox {
  width: 800px;
  margin: 0 auto;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 0 10px #ccc;
  display: inline-block;
}
.chooseBox {
  overflow: auto;
  width: 300px;
  height: 300px;
  color: #333;
  display: inline-block;
}
.chatBox {
  margin: 20px;
  height: 450px;
  overflow: auto;
  box-shadow: inset 0 0 10px #ccc;
  border-radius: 10px;
  background-color: #f2f2f2;
}
.outbox {
  padding: 10px;
  margin-bottom: 50px;
  display: flex;
  justify-content: space-around;
}
textarea {
  height: 160px;
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  outline: none;
  resize: none;
  margin-bottom: 10px;
}
::v-deep .tip {
  color: white;
  text-align: left;
  border-radius: 10px;
  font-family: sans-serif;
  padding: 10px;
  width: auto;
  display: inline-block !important;
}

::v-deep .right {
  background-color: deepskyblue;
}

::v-deep .left {
  background-color: forestgreen;
}

::v-deep .time-text {
  display: flex;
  flex-direction: column;
  display: inline-block !important;
  margin-right: 20px;
}
::v-deep .name-avatar {
  display: flex;
  flex-direction: column;
}
::v-deep .message {
  display: flex;
  justify-content: flex-end;
}
::v-deep .message2 {
  margin-left: 20px;
  display: flex;
  justify-content: flex-start;
}
@media screen and (max-width: 768px) {
  .chooseBox {
    width: 100%;
    height: 20vh;
    color: #333;
    display: inline-block;
  }
  .chatBox {
    width: 90%;
    margin: 20px;
    height: 50vh;
    overflow: auto;
    box-shadow: inset 0 0 10px #ccc;
    border-radius: 10px;
    background-color: #f2f2f2;
  }
  .outbox {
    padding: 10px;
    margin-bottom: 50px;
    display: flex;
    flex-direction: column;
  }
  .chat-outbox {
    width: 100%;
    margin: 0 auto;
    background-color: white;
    border-radius: 10px;
    box-shadow: 0 0 10px #ccc;
    display: inline-block;
  }
}
</style>
